package moonlit.chill.pay.service.impl.ali;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import lombok.extern.slf4j.Slf4j;
import moonlit.chill.pay.cache.PayConfigDataCache;
import moonlit.chill.pay.constants.Constants;
import moonlit.chill.pay.constants.PayType;
import moonlit.chill.pay.service.PayStrategy;
import moonlit.chill.pay.util.AliPayClientUtil;
import moonlit.chill.pay.vo.PayConfig;
import moonlit.chill.pay.vo.TradeParam;
import moonlit.chill.pay.vo.PayResult;
import moonlit.chill.pay.vo.PayResultForQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author MoonlitChill
 * @date 2024/4/15 17:26
 */
@Slf4j
@Service("aliQueryPayStrategy")
public class AliQueryStrategyServiceImpl implements PayStrategy {
    @Resource
    private PayConfigDataCache payConfigDataCache;

    @Autowired
    private AliPayClientUtil aliPayClientUtil;

    @Override
    public PayResult<String> payForPayQuery(TradeParam tradeParam) {
        log.info(String.format("支付宝支付查询参数:%s", JSONUtil.toJsonStr(tradeParam)));
        PayConfig payConfig = payConfigDataCache.getPayConfig();
        PayResult<String> result = new PayResult<>();
        AlipayClient alipayClient = aliPayClientUtil.getAliPayClient(payConfig);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setOutTradeNo(tradeParam.getTransNum());
        request.setBizModel(model);
        if (StrUtil.isNotEmpty(payConfig.getAppAuthToken())){
            request.putOtherTextParam("app_auth_token", payConfig.getAppAuthToken());
        }
        try {
            AlipayTradeQueryResponse queryResponse;
            if (payConfig.getAliType() == 0){
                //证书模式
                queryResponse = alipayClient.certificateExecute(request);
            } else {
                //密钥模式
                queryResponse = alipayClient.execute(request);
            }
            log.info(String.format("支付宝支付查询参数:%s  返回数据:%s", JSONUtil.toJsonStr(tradeParam), JSONUtil.toJsonStr(queryResponse)));
            if (queryResponse.isSuccess()) {
                if ("TRADE_SUCCESS".equals(queryResponse.getTradeStatus()) || "TRADE_FINISHED".equals(queryResponse.getTradeStatus())) {
                    PayResultForQuery resultForQuery = new PayResultForQuery();
                    resultForQuery.setPayType(PayType.ALI);
                    resultForQuery.setPayTime(DateUtil.format(queryResponse.getSendPayDate(), DatePattern.NORM_DATETIME_PATTERN));
                    resultForQuery.setPayStatus(queryResponse.getTradeStatus());
                    resultForQuery.setTransNum(queryResponse.getOutTradeNo());
                    resultForQuery.setOutTradeNo(queryResponse.getTradeNo());
                    result.setSuccess(Boolean.TRUE);
                    result.setResult(JSONUtil.toJsonStr(resultForQuery));
                } else {
                    result.error("订单尚未支付成功", Constants.PAY_FAIL_CODE);
                }
            } else {
                result.error(queryResponse.getSubMsg(), Constants.PAY_FAIL_CODE);
            }
        } catch (AlipayApiException e) {
            result.errorWithException(e.getErrMsg(), Constants.PAY_ERROR_CODE, e);
        }
        return result;
    }
}
